package com.sundayfactory.workpaychart;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

public class DBcontroler {
    private String TAG = this.getClass().getSimpleName();
    private Context mContext;
    workpay_provider provider ;
    SQLiteDatabase database ;
    public DBcontroler(Context context) {
	mContext = context;
	provider = new workpay_provider(context);
	database = provider.database.getWritableDatabase();
    }
    /**
     * 저장되어 있는 년도를 가져온다 
     */
    public String[] getYearlist(){
	Calendar calendar = Calendar.getInstance();
	calendar.setTimeInMillis(System.currentTimeMillis());
	int year = calendar.get(Calendar.YEAR);
	
	String[] list = new String[]{(year-1)+"",(year-2)+"",(year-3)+"",(year-4)+"",(year-5)+""}; 
	return list;
    }
    
    
    
    /**
     * 저장되어있는 노임단가를 불러온다
     */
    public domain_payinfo getYearPayInfo(String year){
	Log.i(TAG, "getYearPayInfo = "+year);
	database = provider.database.getReadableDatabase();
	domain_payinfo detail = new domain_payinfo();
	List<domain_Paylist> domain_payinfos = new ArrayList<domain_Paylist>();
	
	
	Cursor c = database.query("payinfo", new String[]{"code","id","title","pay","year","workercode"}, "year = '"+year+"'", null, null, null, "code ASC");
	
	c.moveToFirst();
	do{
	    if(c.getCount() > 0){
		domain_Paylist item = new domain_Paylist();
		item.setCode(c.getString(0));
		item.setId(c.getString(1));
		item.setTitle(c.getString(2));
		item.setPay(c.getString(3));
		item.setYear(c.getString(4));
		item.setWorkercode(c.getString(5));
		domain_payinfos.add(item);
		
		
	    }
	}while(c.moveToNext());
	detail.setResult(domain_payinfos);
	
	Cursor getdetail = database.query("detail", new String[]{"detail.year","detail.link","detail.workday"}, "detail.year = '"+year+"'", null, null, null, null);
	 if(getdetail.getCount() > 0){
	     	
	    	getdetail.moveToFirst();
        	detail.getDetail().setYear(getdetail.getString(0));
        	detail.getDetail().setLink(getdetail.getString(1));
        	detail.getDetail().setWorkday(getdetail.getString(2));
	 }
	
	
	
	return detail;
    }
    /**
     * 받아온 노임단가 저장
     * @param itemlist
     */
    public void insert_paydata(domain_payinfo info){
	database = provider.database.getWritableDatabase();
	
	ContentValues calues = new ContentValues();
	for(domain_Paylist item : info.getResult()){
	    calues = new ContentValues();
	    calues.put("code", item.getCode());
	    calues.put("id", item.getId());
	    calues.put("pay", item.getPay());
	    calues.put("title", item.getTitle());
	    calues.put("workercode", item.getWorkercode());
	    calues.put("year", item.getYear());
	    Log.i(TAG, "insert_paydata.() = "+item.getTitle());
	    database.insert("payinfo", "", calues);
	}
	
	ContentValues Detail = new ContentValues();
	Detail.put("year", info.getDetail().getYear());
	Detail.put("link", info.getDetail().getLink());
	Detail.put("workday", info.getDetail().getWorkday());
	Log.i(TAG, "insert_paydata.() = "+info.getDetail().getYear());
	Log.i(TAG, "insert_paydata.() = "+info.getDetail().getWorkday());
	Log.i(TAG, "insert_paydata.() = "+info.getDetail().getLink());
	
	
	database.insert("detail", "", Detail);
	
    }
    /**
	 * 내부 DB 확인을 위해 SD 카드로 DB 파일을 복사
	 * @param mContext
	 */
	public void copyDB(Context mContext){
		
		Log.d("MiniApp", "copyDB");
		AssetManager manager = mContext.getAssets();
		String folderPath = "/data/data/com.example.workpaychart/databases";
		String filePath = "/data/data/com.example.workpaychart/databases/workpay.db";
		String outfIle  = Environment.getExternalStorageDirectory().toString()+"/workpay.db";
		File folder = new File(folderPath);
		File file = new File(filePath);
		File outFuile = new File(outfIle);
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		try {
			FileInputStream in = new FileInputStream(file);
			//       InputStream is = manager.open("db/monkey3.db");
			BufferedInputStream bis = new BufferedInputStream(in);

			if (folder.exists()) {

			}else{
				folder.mkdirs();
			}


			if (outFuile.exists()) {
				outFuile.delete();
				outFuile.createNewFile();
			}

			fos = new FileOutputStream(outFuile);
			bos = new BufferedOutputStream(fos);
			int read = -1;
			byte[] buffer = new byte[1024];
			while ((read = bis.read(buffer, 0, 1024)) != -1) {
				bos.write(buffer, 0, read);
			}

			bos.flush();

			bos.close();
			fos.close();
			bis.close();
			in.close();

		} catch (IOException e) {
			e.printStackTrace();
			Log.e("ErrorMessage : ", e.getMessage());
		}
	}
}
